﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using Newtonsoft.Json;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using System.Text.RegularExpressions;
using Microsoft.Phone.Controls.Primitives;
using Coding4Fun.Phone.Controls.Toolkit;
using Microsoft.Phone.Notification;
using Coding4Fun.Phone.Controls;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace YiDingCanWp7
{
    public partial class ShopDetailPivot : PhoneApplicationPage
    {

        Popup popup = new Popup() { IsOpen=false};
         string shopid = string.Empty;
        string url = BaseConfig.BaseUrl+"/Shop/ShopForMobile?shopid={0}";
        string menuUrl = BaseConfig.BaseUrl + "/Shop/ShopSellerCats?shopid={0}";
        ShopDTO shop;
        ShopDTO shopdto;
        public bool MenuLoaded { get; set; }
        public bool IntroLoaded { get; set; }
        public ShopDetailPivot()
        {
            InitializeComponent();
        }
        static bool IsLoaded = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!IsLoaded)
            {
                performanceProgressBar.IsIndeterminate = true;
                try
                {
                    if (this.NavigationContext.QueryString.ContainsKey("shopid"))
                    {
                        shopid = this.NavigationContext.QueryString["shopid"];
                    }
                    var webClient = new WebClient();
                    webClient.OpenReadAsync(new Uri(string.Format(url, shopid)));
                    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);

                    var webClient2 = new WebClient();
                    webClient2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient2_DownloadStringCompleted);
                    webClient2.DownloadStringAsync(new Uri(string.Format(menuUrl, shopid), UriKind.Absolute));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            popup.IsOpen = false;
            
            base.OnNavigatedFrom(e);
        }
        void webClient2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                performanceProgressBar.IsIndeterminate = true;
                List<SellerCatDTO> cats = JsonConvert.DeserializeObject<List<SellerCatDTO>>(e.Result);
                foreach (var item in cats)
                {
                    MenuList.Items.Add(new ListBoxItem() { Content = item.Name, FontSize = 60, Foreground = new SolidColorBrush() { Color = Colors.Red } });
                    RecursionSellerCats(item);
                }
                MenuLoaded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (IntroLoaded && MenuLoaded)
                {
                    performanceProgressBar.IsIndeterminate = false;
                }
            }
        }
        void RecursionSellerCats(SellerCatDTO cat) {
            foreach (var itemdto in cat.Items)
            {
                MenuList.Items.Add(new ListBoxItem() { Content = itemdto.Title + "  " + itemdto.Price, Foreground = new SolidColorBrush() { Color =Colors.Black} });
            }
            if (cat.Children != null && cat.Children.Count > 0)
            {
                foreach (var item2 in cat.Children)
                {
                    MenuList.Items.Add(new ListBoxItem() { Content = item2.Name, FontSize = 60, Foreground = new SolidColorBrush() { Color = Colors.Red } });
                    RecursionSellerCats(item2);
                }
            }
        }
        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                performanceProgressBar.IsIndeterminate = true;
                using (var reader = new StreamReader(e.Result))
                {
                    var returnStrs = reader.ReadToEnd();
                    shop = JsonConvert.DeserializeObject<ShopDTO>(returnStrs);
                    shopdto = shop;
                   // shop.Logo=BaseConfig.BaseUrl + "/upload/shops/" + shop.Id + "_Thumbnails.jpg";
                  //  image_shoplogo.Source = new BitmapImage(new Uri(BaseConfig.BaseUrl + "/upload/shops/" + shop.Id + "_Thumbnails.jpg", UriKind.RelativeOrAbsolute));
                    shopdetail.DataContext = shop;
                    pivot.Title = shop.Title;
                }
                IntroLoaded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally {
                if (IntroLoaded&&MenuLoaded)
                {
                performanceProgressBar.IsIndeterminate = false;
                }
            }
        }

        private void appbar_MakeACall_Click(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"((\d{11})|((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})))",RegexOptions.IgnorePatternWhitespace);
            if (string.IsNullOrEmpty(shop.Phone))
            {
                MessageBox.Show("号码不存在!");
                return;
            }
            MatchCollection mc = regex.Matches(shop.Phone);
            if (mc.Count>1)
            {
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                PopupControl control = new PopupControl();
                foreach (Match item in mc)
                {
                    Button ctrl = new Button();
                    ctrl.Content = item.Value;
                    ctrl.Click += new RoutedEventHandler(ctrl_Click);
                    control.LayoutRoot.Children.Add(ctrl); 
                }
                popup.Child = control;
                popup.IsOpen = true;
            }
            else if(mc.Count>0)
            {
                LatestShopsSettings.Add(shop);
                PhoneCallTask p = new PhoneCallTask();
                p.PhoneNumber = mc[0].Value;
                p.Show();
            }
        }

        void ctrl_Click(object sender, RoutedEventArgs e)
        {
            LatestShopsSettings.Add(shop);
            PhoneCallTask p = new PhoneCallTask();
            p.PhoneNumber = ((Button)sender).Content.ToString();
            p.Show();
            popup.IsOpen = false;
        }

        private void appbar_AddFav_Click(object sender, EventArgs e)
        {
            FavoriteShops.AddFavorate(shopdto);
            ToastPrompt toast = new ToastPrompt(); //实例化 
            toast.Title = "收藏成功"; //设置标题 
           // toast.Message = "收藏成功"; //设置正文消息 
            toast.FontSize = 35; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
           // toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
            toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)
            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show(); 
        }
        void toast_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
        }
        private void appbar_AddComment_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddComment.xaml?shopid=" + shopid, UriKind.RelativeOrAbsolute));
        }
        private void menuItem_ShopFeedback_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ShopFeedbackPage.xaml?shopid=" + shopid, UriKind.RelativeOrAbsolute));
        }
        private void menuItem_ShopComments_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ShopCommentsPage.xaml?shopid=" + shopid, UriKind.RelativeOrAbsolute));
        }
    }
}